import 'dart:ffi';

import 'package:dio/dio.dart';
import 'package:flutter_van_android/models/base_response.dart';
import 'package:flutter_van_android/models/news_ugc_data.dart';
import 'package:flutter_van_android/utils/log_util.dart';
import 'package:oktoast/oktoast.dart';

import '../api/api_client.dart';
import '../api/endpoints.dart';
import '../models/hot_forum_data.dart';
import '../models/login_user.dart';
import '../models/spotLight.dart';
import '../models/ugc_data.dart';
import '../utils/mmkv_util.dart';

/// 用户登录请求
Future<bool> login(String phone, String captcha) async {
  try {
    final baseResponse = await fetchData<LoginUser>(
      Endpoints.userLogin,
      {
        'phone': phone,
        'captcha': captcha,
      },
      (data) => LoginUser.fromJson(data),
    );
    if (baseResponse != null) {
      // 如果请求成功，打印登录 token
      LogUtil.d('登录成功，Token: ${baseResponse.data?.token}');
      MmkvUtil.saveString("token", baseResponse.data!.token);
      return true;
    } else {
      return false;
    }
  } catch (e) {
    // 处理登录失败的情况
    LogUtil.d('登录失败: $e');
    showToast("登录失败！$e");
    return false;
  }
}

//小树知道
Future<List<NewsUgcData>?> getNewsList() async {
  try {
    // 调用 fetchData 获取 Page<UgcData>
    final baseResponse = await fetchData<Page<NewsUgcData>>(
      Endpoints.threeKnowList, // API 地址
      {}, // 请求参数
      (json) => Page<NewsUgcData>.fromJson(
        json,
        (data) => NewsUgcData.fromJson(data),
      ), // 解析逻辑
    );
    if (baseResponse != null) {
      LogUtil.d(baseResponse.data?.dtoList!.length.toString() ?? "没拿到列表");
      return baseResponse.data?.dtoList;
    }
  } catch (e) {
    // 错误处理
    LogUtil.e('请求失败: $e');
  }
  return null;
}

//热帖讨论
Future<List<UgcData>?> getHotPostDiscussion({int page = 1}) async {
  try {
    // 调用 fetchData 获取 Page<UgcData>
    final baseResponse = await fetchData<Page<UgcData>>(
      Endpoints.hotArticleDiscussion, // API 地址
      {
        'page': page,
      }, // 请求参数
      (json) => Page<UgcData>.fromJson(
        json,
        (data) => UgcData.fromJson(data),
      ), // 解析逻辑
      headers: {"version": "1.0.1"},
    );
    if (baseResponse != null) {
      // 获取成功后的处理
      LogUtil.d(baseResponse.data?.dtoList!.length.toString() ?? "没拿到列表");
      return baseResponse.data?.dtoList;
    }
  } catch (e) {
    // 错误处理
    LogUtil.e('请求失败: $e');
  }
  return null;
}

//聚光用户
Future<List<LightUser>?> getLightUserList() async {
  try {
    // 调用 fetchData 获取 Page<UgcData>
    final baseResponse = await fetchData<Page<LightUser>>(
        Endpoints.lightUserList, // API 地址
        {}, // 请求参数
        (json) => Page<LightUser>.fromJson(
              json,
              (data) => LightUser.fromJson(data),
            ), // 解析逻辑
        headers: {"version": "1.0.1"});

    if (baseResponse != null) {
      LogUtil.d(baseResponse.data?.dtoList!.length.toString() ?? "没拿到列表");
      return baseResponse.data?.dtoList;
    }
  } catch (e) {
    // 错误处理
    LogUtil.e('请求失败: $e');
  }
  return null;
} //聚光用户

///获取热门论坛
Future<List<HotForumItem>?> getHotForumList() async {
  try {
    // 调用 fetchData 获取 Page<UgcData>
    final baseResponse = await fetchData<Page<HotForumItem>>(
      Endpoints.hotForumList, // API 地址
      {}, // 请求参数
      (json) => Page<HotForumItem>.fromJson(
        json,
        (data) => HotForumItem.fromJson(data),
      ), // 解析逻辑
    );
    if (baseResponse != null) {
      LogUtil.d(baseResponse.data?.dtoList!.length.toString() ?? "没拿到列表");
      return baseResponse.data?.dtoList;
    }
  } catch (e) {
    // 错误处理
    LogUtil.e('请求失败: $e');
  }
  return null;
}

/// 更新动态点赞状态
Future<List<UgcData>?> articleLikeUpdate(
    {required String ugcId, required Int status}) async {
  try {
    // 调用 fetchData 获取 Page<UgcData>
    final baseResponse = await fetchData<Page<UgcData>>(
      Endpoints.articleLikeUpdate, // API 地址
      {
        'ugcId': ugcId,
        'status': status,
      }, // 请求参数
      (json) => Page<UgcData>.fromJson(
        json,
        (data) => UgcData.fromJson(data),
      ), // 解析逻辑
      headers: {"version": "1.0.1"},
    );

  } catch (e) {
    // 错误处理
    LogUtil.e('请求失败: $e');
  }
  return null;
}

Future<BaseResponse<T>?> fetchData<T>(
  String endpoint,
  Map<String, dynamic> data,
  T Function(Map<String, dynamic>) fromJsonT, {
  Map<String, String>? headers, // 添加可选参数 headers
}) async {
  try {
    Response response = await ApiClient.instance.post(
      endpoint,
      data: data,
      options: Options(headers: headers), // 传递 headers
    );

    // 解析 JSON
    final baseResponse = BaseResponse<T>.fromJson(
      response.data,
      (json) => fromJsonT(json as Map<String, dynamic>),
    );

    if (baseResponse.response == "ok") {
      return baseResponse;
    } else {
      showToast(baseResponse.desc ?? "请求异常");
      return null;
    }
  } catch (e) {
    LogUtil.e('请求失败: $e');
    return null;
  }
}
